package com.bjgov.scoresys.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;

import com.bjgov.scoresys.entity.ProjectItems;
import com.bjgov.scoresys.util.Page;

/**
 * A data access object (DAO) providing persistence and search support for
 * ProjectItems entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .ProjectItems
 * @author MyEclipse Persistence Tools
 */

public class ProjectItemsDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory
			.getLog(ProjectItemsDAO.class);
	// property constants
	public static final String SCORE = "score";
	public static final String TOP_CATE_ID = "topCateId";
	public static final String ITEM_ID = "itemid";

	public void save(ProjectItems transientInstance) {
		log.debug("saving ProjectItems instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(ProjectItems persistentInstance) {
		log.debug("deleting ProjectItems instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	public List<ProjectItems> findByProjectIdTreeId(int projectId, int treeId) {
		log.debug("getting ProjectItems instance with treeid: " + treeId);
		try {
			String queryString = "from ProjectItems as model where model.scoreItem.scoreTree.id= ? and model.project.id= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, treeId);
			queryObject.setParameter(1, projectId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}	
	
	
	public List<ProjectItems> findByProjectIdControlId(int projectId, int controlId) {
		log.debug("getting ProjectItems instance with treeid: " + controlId);
		try {
			String queryString = "from ProjectItems as model where model.scoreItem.scoreTree.id= ? and model.project.id= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, controlId);
			queryObject.setParameter(1, projectId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<ProjectItems> findByProjectId(int projectId) {
		log.debug("getting ProjectItems instance with projectId: " + projectId);
		try {
			String queryString = "from ProjectItems as model where model.project.id= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, projectId);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}	
	
	public int getControlIdScoreSum(int projectId, int controlId) {
		log.debug("getControlIdScoreSum instance");
		try {

			String sql = "select sum(a.score) as num  from project_items a where a.PROJECT_ID = "+projectId+" and a.ControlId_ID ="+controlId;
			return  (Integer)(getSession().createSQLQuery(sql).addScalar("num", Hibernate.INTEGER) ).uniqueResult();
		} catch (RuntimeException re) {
			log.error("getMaxID failed", re);
			//throw re;
			return 0;
		}
	}
	
	/*
	 * 获取当前IDs以外的ID的总和
	 */
	public float getNochangeIdScoreSum(String where, int controlId,int projectId) {
		log.debug("getControlIdScoreSum instance");
		try {

			String sql = "select sum(a.score) as num  from project_items a where a.id not in ("+where+") and a.ControlId_ID ="+controlId+" and a.Project_ID="+projectId;
			return  (Integer)(getSession().createSQLQuery(sql).addScalar("num", Hibernate.INTEGER) ).uniqueResult();
		} catch (RuntimeException re) {
			log.error("getMaxID failed", re);
			//throw re;
			return 0.0f;
		}
	}
	
	public double getProjectIdScoreSum(int projectId)
	{
		log.debug("getControlIdScoreSum instance");
		try {

			String sql = "select sum(a.score) as num  from project_items a where a.PROJECT_ID = "+projectId;
			return  (Double)(getSession().createSQLQuery(sql).addScalar("num", Hibernate.DOUBLE) ).uniqueResult();
		} catch (RuntimeException re) {
			log.error("getMaxID failed", re);
			//throw re;
			return 0;
		}
	}

	public ProjectItems findById(java.lang.Integer id) {
		log.debug("getting ProjectItems instance with id: " + id);
		try {
			ProjectItems instance = (ProjectItems) getSession().get(
					"com.bjgov.scoresys.entity.ProjectItems", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List<ProjectItems> findByIds(String ids) {
		log.debug("getting ProjectItems instance with ids: " + ids);
		try {
			String queryString = "from ProjectItems as model where model.id in(" + ids + ")";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("get ProjectItems with ids: " + ids + " failed", re);
			throw re;
		}
	}	

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ProjectItems instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from ProjectItems as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<ProjectItems> findByScore(Object score) {
		return findByProperty(SCORE, score);
	}

	public List<ProjectItems> findByTopCateId(Object topCateId) {
		return findByProperty(TOP_CATE_ID, topCateId);
	}
	
	public List<ProjectItems> findByItem_ID(Object itemID) {
		return findByProperty(ITEM_ID, itemID);
	}

	public List findAll() {
		log.debug("finding all ProjectItems instances");
		try {
			String queryString = "from ProjectItems";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<ProjectItems> findByProjectIdItemName(int projectId, String itemName) {
		log.debug("findByProjectIdItemName instances");
		try {
			String queryString = "from ProjectItems model where model.project.id=? and model.scoreItem.itemName like ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setInteger(0, projectId);
			queryObject.setString(1, "%" + itemName + "%");
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("findByProjectIdItemName failed", re);
			throw re;
		}
	}
	
	public ProjectItems merge(ProjectItems detachedInstance) {
		log.debug("merging ProjectItems instance");
		try {
			ProjectItems result = (ProjectItems) getSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ProjectItems instance) {
		log.debug("attaching dirty ProjectItems instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ProjectItems instance) {
		log.debug("attaching clean ProjectItems instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	@Override
	public int count() {
		log.debug("getProjectItemsCount");
		try {
			String queryString = "select count(id) from ProjectItems";
			Query query = getSession().createQuery(queryString);
	        return (Integer) query.iterate().next();
		} catch (RuntimeException re) {
			log.error("getProjectItemsCount failed", re);
			throw re;
		}
	}

	@Override
	public List getByPage(Page page) throws HibernateException {
		String querySentence = "from ProjectItems";
		Query query = getSession().createQuery(querySentence);
		// 实现分页功能
		query.setFirstResult(page.getBeginIndex())
		.setMaxResults(page.getEveryPage());
		return query.list();
	}		
}